package com.kl.forum.service;


import com.alibaba.fastjson.JSONObject;
import com.kl.forum.dao.MemberMapper;
import com.kl.forum.dao.NoviceTaskRecordMapper;
import com.kl.forum.dao.NoviceUserRecordMapper;
import com.kl.forum.dao.SignMapper;
import com.kl.forum.entity.Member;
import com.kl.forum.entity.NoviceTaskRecord;
import com.kl.forum.entity.NoviceUserRecord;
import com.kl.forum.entity.Sign;
import com.kl.forum.enums.DictDailyTaskEnum;
import com.kl.forum.enums.DictNoviceEnum;
import com.kl.forum.enums.ResultCode;
import com.kl.forum.util.ResultInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class NoviceTaskService {
    @Autowired
    private NoviceTaskRecordMapper noviceTaskRecordMapper;
    @Autowired
    private NoviceUserRecordMapper noviceUserRecordMapper;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private SignMapper signMapper;


    public ResultInfo pageInfo(Integer userId) {
        ResultInfo re=new ResultInfo();
        Map<String,Object> map=new HashMap<>();
        // 先判断user_record里有没有数据 ，有表示已经完成所有任务
        NoviceUserRecord record = noviceUserRecordMapper.findUserRecord(userId);
        if (null != record && record.getTakedFlag() == 0) {
            // 完成所有任务未领奖
            finishRes(map);
            map.put("award", 1);
            re.setData(map);
            re.setMessage(ResultCode.SUCCESS.getMsg());
            re.setCode(ResultCode.SUCCESS.getCode());
            return  re;
        } else if (record != null && record.getTakedFlag() == 1) {
            // 已领奖
            finishRes(map);
            map.put("award", 0);
            re.setData(map);
            re.setMessage(ResultCode.SUCCESS.getMsg());
            re.setCode(ResultCode.SUCCESS.getCode());
            return  re;
        }
        boolean finishAllTask = false;
        int totalCoin = 0;
        initRes(map);
        if (null == record) {
            // 没有的话，分5步判断各个任务是否已经完成
            // 1.手机
            boolean mobileRes = checkMobile(userId);
            if (mobileRes) {
                totalCoin += DictNoviceEnum.MOBILE.getCoins();
                map.put("mobile", 1);
            }
            // 2.连续三天签到
            Sign sign= signMapper.findSignByUserId(userId);
            boolean signRes = checkSign(userId);
            if (signRes) {
                totalCoin += DictNoviceEnum.SIGN3DAYS.getCoins();
                map.put("sign3Days", 1);
                map.put("sign3DaysPro", 3);
            }else{
                if (sign==null){
                    map.put("sign3DaysPro", 0);
                }else {
                    map.put("sign3DaysPro", sign.getDayNum());
                }
            }
            // 3.提现
            boolean withDrawSign = checkWithDraw(userId);
            if (withDrawSign) {
                totalCoin += DictNoviceEnum.CASH.getCoins();
                map.put("withDraw", 1);
            }
            // 4.跑步游戏
            boolean runGameRes = checkRunGame(userId);
            if (runGameRes) {
                totalCoin += DictNoviceEnum.RUNGAME.getCoins();
                map.put("runGame", 1);
            }
            // 5.日常任务
            boolean dailyTaskRes = checkDailyTask(userId, map);
            if (dailyTaskRes) {
                totalCoin += DictNoviceEnum.DAYILTASK.getCoins();
                map.put("dailyTask", 1);
            }
            finishAllTask = mobileRes && signRes && withDrawSign && runGameRes && dailyTaskRes;
            map.put("coins", totalCoin);
        }
        if (finishAllTask) {
            // 5个任务都完成后，插入数据到user_record表内
//            new NoviceUserRecord().setUserId(userId).setCreateTime(new Date()).save();
            NoviceUserRecord noviceUserRecord=new NoviceUserRecord();
            noviceUserRecord.setUserId(userId);
            noviceUserRecord.setCreateTime(new Date());
            noviceUserRecordMapper.insertSelective(noviceUserRecord);
            map.put("award", 1);
        } else {
            map.put("award", 0);
        }
        re.setData(map);
        re.setMessage(ResultCode.SUCCESS.getMsg());
        re.setCode(ResultCode.SUCCESS.getCode());
        return  re;
    }

    /**
     * 校验日常任务是否完成
     *
     * @return true可以修改dailyTask的值
     */
    private boolean checkDailyTask(Integer userId, Map<String, Object> map) {
        List<NoviceTaskRecord> rList=   noviceTaskRecordMapper.checkDailyTask(userId,DictNoviceEnum.DAYILTASK.getId());
        List<Integer> idList = DictDailyTaskEnum.idList();
        for (NoviceTaskRecord record : rList) {
            for (DictDailyTaskEnum dailyTask : DictDailyTaskEnum.values()) {
                if (record.getDailyType()== dailyTask.getId()) {
                    // 完成移除
                    idList.remove(new Integer(dailyTask.getId()));
                    // 修改对应key的value
                    map.put(dailyTask.getTitle(), 1);
                }
            }
        }
        // 移除空了，表示全部完成
        if (idList.isEmpty()) {
            return true;
        }
        return false;
    }

    private boolean checkRunGame(Integer userId) {
       int n= noviceTaskRecordMapper.checkRunGame(userId, DictNoviceEnum.RUNGAME.getId());
        if(n>=1){
            return  true;
        }else {
            return  false;
        }
    }

    private boolean checkWithDraw(Integer userId) {
      int n=  noviceTaskRecordMapper.checkWithDraw(userId,DictNoviceEnum.CASH.getId());
      if(n>=1){
           return  true;
      }else {
          return  false;
      }
    }

    private boolean checkSign(Integer userId) {
      Sign sign= signMapper.findSignByUserId(userId);
      if (sign!=null){
          if (sign.getStatus()==0){
               return  true;
          }else{
              return  false;
          }
      }else {
          return  false;
      }
    }

    private boolean checkMobile(Integer userId) {
       int n= memberMapper.checkMobile(userId);
       if(n==0){
           return  true;
       }else{
           return false;
       }
    }


    /**
     * 填充返回值
     */
    public Map<String, Object> finishRes(Map<String, Object> map) {
        map.put("coins", DictNoviceEnum.FINISH.getCoins());
        map.put("mobile", 1);
        map.put("sign3Days", 1);
        map.put("sign3DaysPro", 3);
        map.put("withDraw", 1);
        map.put("runGame", 1);
        map.put("dailyTask", 1);
        map.put("post", 1);
        map.put("comment", 1);
        map.put("like", 1);
        map.put("beLiked", 1);
        map.put("sharePost", 1);
        map.put("shareMoney", 1);
        return map;
    }
    /**
     * 都未完成的返回值
     */
    public Map<String, Object> initRes(Map<String, Object> map) {
        map.put("coins", 0);
        map.put("mobile", 0);
        map.put("sign3Days", 0);
        map.put("withDraw", 0);
        map.put("runGame", 0);
        map.put("dailyTask", 0);
        map.put("post", 0);
        map.put("comment", 0);
        map.put("like", 0);
        map.put("beLiked", 0);
        map.put("sharePost", 0);
        map.put("shareMoney", 0);
        return map;
    }


    public String takeAward(Integer userId) {
        // 先判断user_record里有没有数据 ,是不是领取过
        NoviceUserRecord record = noviceUserRecordMapper.findUserRecord(userId);
        synchronized (NoviceUserRecord.class) {
            if (null == record) {
                return "请完成所有任务再领奖";// 未完成
            }
            if (record.getTakedFlag() == 1) {
                return "您已经领取了奖励，不能重复领取";// 已领取
            }
            if (record.getTakedFlag() == 0) {
                // 修改take_flag状态
//                updateTakedFlag(userId);
                noviceUserRecordMapper.updateTakedFlag(userId);
                // 修改用户金币余额t_member表
                Member member =memberMapper.findUserByUserId(userId);
                Integer oldCoin = member.getCoinNumber();
                Integer newCoin = oldCoin + 1000;
                member.setCoinNumber(newCoin);
                memberMapper.updateByPrimaryKeySelective(member);
                return "领取成功";// 领取成功
            }
        }
        return "领取失败";
    }

    public ResultInfo checkFinish(Integer userId) {
        ResultInfo re=new ResultInfo();
        Map<String,Object>  map = new JSONObject();
        map.put("takedFlag", false);
        NoviceUserRecord record = noviceUserRecordMapper.findUserRecord(userId);
        if (record != null && record.getTakedFlag() == 1) {// 已领取返回true
            map.put("takedFlag", true);
        }
        re.setData(map);
        re.setMessage(ResultCode.SUCCESS.getMsg());
        re.setCode(ResultCode.SUCCESS.getCode());
        return  re;
    }
}
